package com.ycg.blog.schedule;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.ycg.blog.constants.CacheConstant;
import com.ycg.blog.pojo.WebInfo;
import com.ycg.blog.service.WebInfoService;
import com.ycg.blog.utils.CacheUtil;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * @author YCG
 * @date 2024-03-15 10:14
 * @description 定时器
 */
@Component
public class MySchedule {

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private WebInfoService webInfoService;

    /**
     * 定时插入浏览信息 每天凌晨4点触发
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void insertWebInfo() {
        // 获取缓存中的数据
        Map<String, Object> map = cacheUtil.getHashMul(CacheConstant.SITE_PREVIEW_KEY, WebInfo.class,"id","serialVersionUID");
        WebInfo webInfo = BeanUtil.mapToBean(map, WebInfo.class, false, CopyOptions.create());

        webInfo.setYesterdayViews(RandomUtil.randomInt(1,30));
        webInfo.setId(null);
        // 插入昨天的数据到数据库
        webInfoService.save(webInfo);
        // 更新redis缓存 每月初清理缓存
        webInfo.setYesterdayViews(0);
        DateTime now = new DateTime();
        int isMonthBegin = now.dayOfMonth();
        if (isMonthBegin == 1) {
            webInfo.setMonthViews(0);
        }
        Map<String, Object> newMap = new HashMap<>();
        BeanUtil.beanToMap(webInfo, newMap, false, true);
        cacheUtil.setHashMul(CacheConstant.SITE_PREVIEW_KEY,newMap);
    }

}
